from django.shortcuts import render
from django.views import View
from django import http

from collections import OrderedDict
from .models import Content, ContentCategory
from apps.goods.models import GoodsChannel, GoodsCategory, GoodsChannelGroup


# Create your views here.
class IndexView(View):
    def get(self, request):
        categories = OrderedDict()

        # 查询 商品频道表
        channels = GoodsChannel.objects.order_by('group_id', 'sequence')
        # 遍历37个频道
        for channel in channels:
            # 每个频道--外键属性
            group_id = channel.group_id
            # 判断当前字典
            if group_id not in categories:
                categories[group_id] = {'channels': [], 'sub_cats': []}

            # 频道chanel根据category_id,取出一级分类
            cat1 = channel.category
            cat1.url = channel.url
            categories[group_id]['channels'].append(cat1)

            # 一级--取二级--三级
            for cat2 in cat1.subs.all():
                cat2.sub_cats = []
                # 二级取三级
                for cat3 in cat2.subs.all():
                    cat2.sub_cats.append(cat3)
                categories[group_id]['sub_cats'].append(cat2)

        # 获取广告数据
        contents = {}
        content_categories = ContentCategory.objects.all()
        # 遍历广告分类
        for cat in content_categories:
            contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

        # 构建前端数据
        context = {
            'categories': categories,
            'contents': contents,
        }
        # 返回渲染的模板文件
        return render(request, 'index.html', context)



